package chances.framework.jpa;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.repository.support.Repositories;

public class RepositoryHelper {
	
	Repositories repositories;
	

	PersistentEntities persistentEntities;
	
	
	
	private Map<String, Class<?>> alias = new ConcurrentHashMap<String, Class<?>>();

	
	public Object getRepository(Class<?> clazz){
		Object result = this.repositories.getRepositoryFor(clazz);
		return result;
	}
	
	public RepositoryHelper(ApplicationContext applicationContext){
		this.repositories = createRepositories(applicationContext);
		this.persistentEntities =createPersistentEntities(applicationContext);
		this.persistentEntities.forEach(s->{
			Class<?> clazz = s.getType();
			String name = captureName(clazz.getSimpleName());
			alias.put(name, clazz);
		});
	}
	
	public Class<?> getEntityType(String name){
		return this.alias.get(name);
	}


	public static Repositories createRepositories(ApplicationContext applicationContext) {
		return new Repositories(applicationContext);
	}

	
	public static PersistentEntities createPersistentEntities(ApplicationContext applicationContext) {
		List<MappingContext<?, ?>> arrayList = new ArrayList<MappingContext<?, ?>>();
		for (MappingContext<?, ?> context : BeanFactoryUtils
				.beansOfTypeIncludingAncestors(applicationContext, MappingContext.class).values()) {
			arrayList.add(context);
		}
		return new PersistentEntities(arrayList);
	}

	public static String captureName(String name) {
		char[] cs = name.toCharArray();
		cs[0] = Character.toLowerCase(cs[0]);
		return String.valueOf(cs);

	}

}
